#!/usr/bin/env python
#-*- coding:utf-8 -*-
from prettytable import PrettyTable
import datetime
import os
ShopList = {} #商品菜单
UserShopList = [] #用户已买菜单
ShopName = [] #商品名字
ShopPrice = [] #商品价格
NumList = [] #编号
ByShopTime = [] #商品购买时间
UserMoney = 0 #用户金钱
ShopNum = [] #商品数量
AdminUser = [] #管理员用户
AdminPassWd = [] #管理员密码
def ReadAdmin():#读取管理员账户以及密码
    UserInfo = open('Admin.txt',mode='r',encoding='utf-8')
    for lines in UserInfo:
        AdminUser.append(lines[0:lines.index(':')])
        AdminPassWd.append(lines[(lines.index(':')+1):].strip())
    return AdminUser,AdminPassWd
def ReadShop():#读取商品列表
    ReadShopList = open('ShopList.txt',mode='r',encoding='utf-8')
    num = 1
    for lines in ReadShopList:
        key = lines[0:lines.index(':')]
        value = lines[(lines.index(':')+1):lines.index(',')]
        ShopList[key] = int(value)
        ShopNum.append(int(lines[lines.index(',') + 1:].strip()))
        ShopName.append(key)
        ShopPrice.append(value)
        NumList.append(num)
        num += 1
    return ShopList,ShopNum,ShopName,ShopPrice,NumList
def PrintShop():#打印商品列表
    num = 1
    form = PrettyTable(['编号','商品','价格','余量']) #定义表头
    for i in ShopList: #定义表格内容
        if ShopNum[num - 1] > 0 :
            form.add_row([num,i,ShopList[i],ShopNum[num - 1]])
            num += 1
        elif UserName in AdminUser:
            form.add_row([num, i, ShopList[i],ShopNum[num - 1]])
            num += 1
        else:
            form.add_row([num, i, ShopList[i], '已销售完'])
            num += 1
    form.align = 'l' #所有内容左对齐
    print(form)
def PrintUserShop():
    num = 0
    form = PrettyTable(['编号','商品','购买时间',]) #和上面PrintShop一样的逻辑
    for i in UserShopList:
        form.add_row([num+1,i,ByShopTime[num]])
        num += 1
    form.align = 'l'
    print(form)
def PasswdNoSee(a):#密码不可见
    import msvcrt, os
    print(a, end='', flush=True)
    li = []
    while 1:
        ch = msvcrt.getch()
        #回车
        if ch == b'\r':
            return b''.join(li).decode() #把list转换为字符串返回
            break
        #退格
        elif ch == b'\x08':
            if li:
                li.pop()
                msvcrt.putch(b'\b')
                msvcrt.putch(b' ')
                msvcrt.putch(b'\b')
        #Esc
        elif ch == b'\x1b':
            break
        else:
            li.append(ch)
            msvcrt.putch(b'*')
    return b''.join(li).decode()##
def UserChoose():
    print('欢迎光临小张牌购物车'.center(50,'*'))
    PrintShop()
    print('请输入你要购买的商品名或者编号')
    input('>>>').strip()
    print('您还没有登录！怎么操作嘛')
    while True:
        print('是否登录？（y/n）')
        UserChoose = input('>>>').strip()
        if UserChoose.lower() == 'y' or UserChoose == '是':
            return 1
        elif UserChoose.lower() == 'n' or UserChoose == '否':
            print('那有缘再见！')
            exit()
        else:
            print('输入有误！')
def UserLogin():#用户登录
    while True:
        UserName = input('请输入用户名：').strip()
        if UserName in AdminUser:
            num = 0
            while True:
                if num <= 3:
                    AdminPass = PasswdNoSee('请输入密码：')
                    print('\n')
                    if AdminPass == AdminPassWd[AdminUser.index(UserName)]:
                        PassWd = AdminPassWd
                        while True:
                            print("请选择以管理员登录或者普通用户？")
                            print("1.管理员\t2.用户")
                            UserChoose = input('>>>').strip()
                            if UserChoose == '1' or UserChoose == '管理员':
                                return 1,UserName
                            elif UserChoose == '2' or UserChoose == '用户':
                                return  1.5,UserName
                            else:
                                print('输入有误')
                    else:
                        print('密码错误！')
                        num += 1
                else:
                    print('错误次数过多！')
                    exit()
        elif os.path.exists('%s_date.txt'%(UserName)) == True:#判断是否存在日志文件
            return 2,UserName
        else:
            return 3
def NewUser():
    print("没有这个用户的啦~是不是要创建啦~")
    while True:
        UserName = input('请输入用户名：')
        while True:
            PassWd1 = PasswdNoSee('请输入密码：')
            PassWd2 = PasswdNoSee('请再次输入密码：')
            if PassWd1 == PassWd2:
                with open('%s_date.txt' % (UserName), mode='w', encoding='utf-8') as f:
                    f.write(PassWd1)
                print('您已成功创建用户')
                return UserName,PassWd
            else:
                print('两次密码不对请重新输入')
def ReadUserInfo():
    with open('%s_date.txt' % (UserName), mode='r', encoding='utf-8') as UserInfo:
        PassWd = str(UserInfo.readline()).strip()  # 读取密码
        UserShopList = UserInfo.readline().strip().split(',')  # 读取已买商品名
        UserShopList.pop()  # 删除列表最后一个空的
        ByShopTime = UserInfo.readline().strip().split(',')  # 读取已买商品时间
        ByShopTime.pop()  # 删除列表最后一个空的
        UserMoney = int(UserInfo.readline())  # 读取用户余额
    return PassWd,UserShopList,ByShopTime,UserMoney
def AdminAsUser():
    while True:
        print('以普通用户还是测试用户登录？')
        print('\t1.普通用户\t2.测试用户')
        UserChoose = input('>>>').strip()
        if UserChoose == '1' or UserChoose == '普通用户' or UserChoose == '普通':
            return 1
        elif UserChoose == '2' or UserChoose == '测试' or UserChoose == '测试用户':
            return 2
        else:
            print('输入有误！')
def Shoop1(): #普通用户购买以及管理员已普通用户身份登录的
    while True:
        print('欢迎光临小张购物车')
        PrintShop()
        print('可以输入商品名或者编号进行购买')
        print('\t1.q(退出)\t2.cx(查询)\t3.cz（充值）')
        Choose = input('>>>').strip()
        if Choose in ShopName or Choose in NumList:
            while True:
                print('请输入购买数量：')
                Choose1 = input('>>>')
                if Choose1.isdigit():
                    Choose1 = int(Choose1)
                    if UserMoney> ShopPrice[ShopName.index(Choose)]*Choose1 :
                        Money = UserMoney - ShopPrice[ShopName.index(Choose)]*Choose1
                        ShopNum[ShopName.index(Choose)] -= Choose1
                        for i in range(0,Choose1):
                            UserShopList.append(Choose)
                            Time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                            ByShopTime.append(Time)
                        return ShopNum,Money,UserShopList,ByShopTime
                    elif UserMoney>ShopPrice[NumList.index(Choose)]*Choose1 :
                        Money = UserMoney - ShopPrice[NumList.index(Choose)] * Choose1
                        ShopNum[NumList.index(Choose)] -= Choose1
                        for i in range(0,Choose1):
                            UserShopList.append(Choose)
                            Time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                            ByShopTime.append(Time)
                        return ShopNum, Money,UserShopList,ByShopTime
                    else:
                        print('您的余额不足')
                else:
                    print('请输入正确数字！')
        elif Choose.lower() == 'q' or Choose == '退出':
            return '退出'
        elif Choose.lower() ==  'cx' or Choose == '查询':
            PrintUserShop()
        elif Choose.lower() ==  'cz' or Choose == '充值':
            Money = AddUserMoney()
        else:
            print('输入有误！')
def AddUserMoney(a):
    if UserMoney > 0 :
        while True:
            print('是否充值？')
            Choose = input(">>>").strip()
            if Choose == '是' or  Choose.lower() == 'y' or Choose.lower() == '充值':
                while True:
                    Money = input(a).strip()
                    if Money.isdigit():
                        Money = UserMoney + int(Money)
                        return Money
                    else:
                        print('请输入正确数字')
            elif Choose == '否' or  Choose.lower() == 'n' :
                print('好吧，那您的钱不会改变')
                return UserMoney
            else:
                print('输入有误！')
    else:
        while True:
            Money = input(a).strip()
            if Money.isdigit():
                Money = UserMoney + int(Money)
                return Money
            else:
                print('请输入正确数字')
Result = ReadAdmin()
AdminUser = Result[0]
AdminPassWd = Result[1]
Result = ReadShop()
ShopList = Result[0]
ShopNum = Result[1]
ShopName = Result[2]
ShopPrice = Result[3]
NumList = Result[4]
UserChoose()
Result = UserLogin()
if 1 in Result: #管理员
    UserName = Result[1]
elif 1.5 in Result:#管理员用户选择用户登录
    UserName = Result[1]
    Result = AdminAsUser()
    if Result == 1:
        while True:
            print(1)
    else:
        while True:
            print(123)
elif 2 in Result : #普通用户登录
    UserName = Result[1]
    Result = ReadUserInfo()
    PassWd = Result[0]
    UserShopList = Result[1]
    ByShopTime = Result[2]
    UserMoney = Result[3]
    while True:
        Result = Shoop1()
        if len(Result)
elif Result == 3: #新建用户
    Result = NewUser()
    UserName = Result[0]
    PassWd = Result[1]
    UserMoney = AddUserMoney('请输入money：')